<template>
  <div class="app-container">
    <Sidebar
      :conversations="conversations"
      @select="handleSelectConversation"
      @new-chat="handleNewChat"
    />

    <div class="chat-container">
      <div class="chat-header">
        <h2>{{ conversationName || "新对话" }}</h2>
      </div>

      <div class="chat-messages" ref="messagesContainer">
        <!-- 欢迎消息 -->
        <ChatMessage :message="{ answer: welcomeMessage }" type="answer" />

        <!-- 对话消息 -->
        <template v-for="(msg, index) in messages" :key="index">
          <!-- 用户问题 -->
          <ChatMessage
            v-if="msg.question"
            :message="{ question: msg.question }"
            type="question"
          />
          <!-- AI回答 -->
          <ChatMessage
            v-if="msg.answer"
            :message="{ answer: msg.answer }"
            type="answer"
          />
        </template>
      </div>

      <div class="chat-input-container">
        <ChatInput
          @send="handleSendQuestion"
          :loading="isLoading"
          :disabled="false"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, watch, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import Sidebar from "../AI/Sidebar.vue";
import ChatInput from "../AI/ChatInput.vue";
import ChatMessage from "../AI/ChatMessage.vue";
import useApi from "../AI/useApi";

export default {
  components: { Sidebar, ChatInput, ChatMessage },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const api = useApi();
    const messages = ref([]);
    const conversations = ref([]);
    const conversationName = ref("");
    const messagesContainer = ref(null);
    const isLoading = ref(false);
    const conversationId = ref("");
    const welcomeMessage =
      "我是问答系统小琳，我可以帮你解决IT行业、医疗行业和人事行业的问题，请把你的问题告诉我";

    const validateConversationId = () => {
      if (!conversationId.value || conversationId.value === "undefined") {
        console.error("无效的会话ID:", conversationId.value);
        return false;
      }
      return true;
    };

    const fetchConversations = async () => {
      try {
        conversations.value = await api.getAllConversations(
          localStorage.getItem("userid")
        );
      } catch (error) {
        console.error("加载会话列表失败:", error);
      }
    };

    const loadConversation = async () => {
      conversationId.value = route.params.id;
      if (!validateConversationId()) return;

      try {
        isLoading.value = true;
        const details = await api.getConversationDetails(conversationId.value);

        // 重置消息，只保留从API获取的对话记录
        messages.value = details.map((item) => ({
          question: item.question || "",
          answer: item.answer || "",
          timestamp: item.created_at,
        }));

        if (details.length > 0) {
          conversationName.value = details[0].question;
        }
      } catch (error) {
        console.error("加载会话失败:", error);
      } finally {
        isLoading.value = false;
        scrollToBottom();
      }
    };

    const scrollToBottom = () => {
      nextTick(() => {
        if (messagesContainer.value) {
          messagesContainer.value.scrollTop =
            messagesContainer.value.scrollHeight;
        }
      });
    };

    const handleSendQuestion = async (question) => {
      if (!question.trim() || !validateConversationId()) return;

      try {
        isLoading.value = true;

        // 添加用户问题
        messages.value.push({
          question: question,
          answer: "", // 先留空，等待AI回答
          timestamp: new Date().toISOString(),
        });

        scrollToBottom();

        // 获取AI回答
        const response = await api.getAnswer(conversationId.value, question);
        const aiAnswer =
          typeof response === "string"
            ? response
            : response && (response.answer ?? response.text);
        // 更新最后一条消息的AI回答（兼容不同返回结构）
        messages.value[messages.value.length - 1].answer = aiAnswer || "";

        // 如果是第一个问题，更新会话名称
        if (messages.value.length === 1) {
          await api.updateConversationName(conversationId.value, question);
          conversationName.value = question;
          await fetchConversations();
        }
      } catch (error) {
        console.error("发送问题失败:", error);
        // 出错时也更新最后一条消息的AI回答
        messages.value[messages.value.length - 1].answer =
          "获取回答时出错，请稍后再试";
      } finally {
        isLoading.value = false;
        scrollToBottom();
      }
    };

    const handleSelectConversation = (id) => {
      router.push({ name: "chat", params: { id } });
    };

    const handleNewChat = () => {
      router.push({ name: "home" });
    };

    onMounted(() => {
      fetchConversations();
      loadConversation();
    });
    watch(() => route.params.id, loadConversation);

    return {
      messages,
      conversations,
      conversationName,
      messagesContainer,
      isLoading,
      welcomeMessage,
      handleSendQuestion,
      handleSelectConversation,
      handleNewChat,
    };
  },
};
</script>

<style scoped>
.app-container {
  display: flex;
  height: calc(100vh - 70px);
  padding-top: 70px;
  background: linear-gradient(180deg, #f9fbff 0%, #ffffff 100%);
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;
  border-left: 1px solid #eef0f3;
}

.chat-header {
  position: sticky;
  top: 0;
  padding: 1rem 1.25rem;
  border-bottom: 1px solid #eef0f3;
  background-color: rgba(250, 250, 250, 0.9);
  backdrop-filter: saturate(180%) blur(6px);
  z-index: 1;
}

.chat-header h2 {
  margin: 0;
  font-size: 1.25rem;
  color: #333;
  font-weight: 500;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 1.25rem 1.25rem 0.75rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  background: linear-gradient(180deg, #fcfdff 0%, #f7f9fc 100%);
}

.chat-input-container {
  position: sticky;
  bottom: 0;
  padding: 0.75rem 1rem 1rem;
  border-top: 1px solid #eef0f3;
  background-color: rgba(255, 255, 255, 0.95);
  backdrop-filter: saturate(180%) blur(6px);
}
</style>
